/*
 * @Author: Swance
 * @Date: 2023-12-14
 * @Description: 画布自适应浏览器视口插件
 */

import { fabric } from 'fabric';
import { useDebounce } from '@/hooks/useDebounce.ts';
import { IEditor } from '@/types/global';

// 画布大小响应浏览器视口 插件
class ResizePlugin {
  canvas: fabric.Canvas;
  editor: IEditor;
  func: any;
  static pluginName = 'ResizePlugin';
  static apis = ['addResizeListener', 'removeResizeListener'];
  constructor(canvas: fabric.Canvas, editor: IEditor) {
    this.canvas = canvas;
    this.editor = editor;
    this.func = useDebounce(this, this.setWindowSize, 60);
    this.func();
    this.addResizeListener();
  }

  setWindowSize() {
    const width =
      window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth;
    const height =
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight;
    this.canvas.setDimensions({ width, height });
  }

  addResizeListener() {
    window.addEventListener('resize', this.func);
  }

  removeResizeListener() {
    window.removeEventListener('resize', this.func);
  }
}

export default ResizePlugin;
